<script setup lang="ts">
declare global {
  interface Window {
    VConsole: any
  }
}

const appStore = useAppStore()
const { currentGlobalCurrency, isLogin, userInfo, mqttIsConnected } = storeToRefs(appStore)
const { VITE_SOCKET_PREFIX } = getEnv()

const minuteTimestamp = Math.floor(Date.now() / 60000)
useHead({
  meta: [
    {
      name: 'viewport',
      content: 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
    },
  ],
  script: [
    {
      src: `https://cstaticdun.126.net/load.min.js?t=${minuteTimestamp}`,
      defer: true,
    },
    {
      src: 'https://unpkg.com/vconsole@latest/dist/vconsole.min.js',
      type: 'text/javascript',
      onload: () => {
        const vConsole = new window.VConsole()
      },
    },
  ],
})

const stop = watch([isLogin, userInfo], ([_isLogin, _userInfo], [oLogin]) => {
  if (_isLogin && _userInfo?.uid) {
    socketClient.connect('登录连接')

    appStore.runGetVipConfig()
    const globalCurrencyCode = currencyConfig[currentGlobalCurrency.value]?.cur ?? '701'
    const currency_id = supportedCur.includes(globalCurrencyCode) ? globalCurrencyCode : '706'
    appStore.runAsyncRebateAutomatic(currency_id)
    stop()
  }
})

watch([isLogin, userInfo, mqttIsConnected], ([_isLogin, _userInfo, _mqttIsConnected], [oldIsLogin, oldUserInfo, oldMqttIsConnected]) => {
  if (
    _isLogin && _userInfo?.uid && _mqttIsConnected
    && (_isLogin !== oldIsLogin || _userInfo?.uid !== oldUserInfo?.uid || _mqttIsConnected !== oldMqttIsConnected)
  ) {
    socketClient.addSubscribe(`${VITE_SOCKET_PREFIX}/balance/${_userInfo?.uid}`, { callback: balanceMsgCallback })
    socketClient.addSubscribe(`${VITE_SOCKET_PREFIX}/member/${_userInfo?.uid}`, { callback: memberCallback })
    socketClient.addSubscribe(`${VITE_SOCKET_PREFIX}/member/notifications/${_userInfo?.uid}`, { callback: notificationMsgCallback })
    socketClient.addSubscribe('/zk/currency/status', { callback: balanceMsgCallback })
    // socketClient.addSubscribe(`${VITE_SOCKET_PREFIX}/promo/deposit/${_userInfo?.uid}`, { callback: promoDepositCallback })
    socketClient.addSubscribe(`${VITE_SOCKET_PREFIX}/promo/fixed/deposit`, { callback: promoFixedDepositCallback })
    socketClient.addSubscribe(`${VITE_SOCKET_PREFIX}/kyc/${_userInfo?.uid}`, { callback: kycVerifyMsgCallBack })
  }
})

// 使用 onMounted 确保在组件挂载后执行初始化
onMounted(async () => {
  const { initTheme } = useTheme()
  // 使用 onMounted 确保在组件挂载后执行初始化
  try {
    // 初始化品牌信息
    const brandStore = useBrandStore()
    await brandStore.runAsyncBrandBaseDetail()

    // 执行全局初始化
    await globalInit()

    // 初始化主题
    initTheme()
    // 没登录连接
    if (!isLogin.value)
      socketClient.connect('没登录连接')
  }
  catch (error) {
    console.error('应用初始化失败:', error)
    // 这里可以添加错误处理逻辑，比如显示错误提示等
  }
  appEventBus.on(EventBusNames.NEED_LOGiN_MSG, () => {
    i18nNavigateTo('/login/signin')
  })
  appEventBus.on(EventBusNames.REFRESH_BALANCE_BUS, () => {
    appStore.getBalanceData()
  })
  appEventBus.on(EventBusNames.REFRESH_MEMBER_BUS, () => {
    appStore.updateUserInfo()
  })

  /* appEventBus.on(EventBusNames.RECEIVE_FLUTTER_APP_MSG, (p: FlutterAppMsgType) => {
    const currencyType = p.msg.currency
    switch (p.type) {
      case ReceiveFlutterAppMessage.CURRENCY_CHANGE:
        if (currencyType) {
          appStore.changeGlobalCurrency(currencyType)
          sessionStorage.setItem('current_global_currency', currencyType)
        }
        break
    }
  }) */

  /** 监听kyc验证成功通知 */
  /* appEventBus.on(EventBusNames.KYC_VERIFY_SUCCESS, () => {
    openNotify({
      title: t('success_verify'),
      message: t('kyc_is_good'),
    })
    appStore.runGetMemberKYCInfo()
  }) */

  /** 监听存款成功通知，并在没有钱包弹窗时、后台打开PWA时打开PWA弹窗 */
  /* appEventBus.on(EventBusNames.FINANCE_DEPOSIT_SUCCESS, () => {
    console.log('🚸🚸🚸 ~ appEventBus.on ~ FINANCE_DEPOSIT_SUCCESS:收到存款成功的通知')
    if (isDepositPWAOpen.value) {
      // 钱包弹窗是关闭状态
      if (!isWalletDialogOpen.value && !isPwa())
        openPwaDialog()

      // 钱包弹窗是打开状态
      else
        setIsHaveWaitingPWADialogTrue()
    }
  }) */
})

// 添加错误处理
onErrorCaptured((err, instance, info) => {
  console.error('捕获到错误:', err)
  console.error('错误信息:', info)
  return false // 阻止错误继续传播
})
</script>

<template>
  <div>
    <!--    <AppGlobalStatistics /> -->
    <AppGlobalWatch />
    <AppGlobalSetInterval />
    <AppGlobalMounted />
    <AppGlobalLimited />
    <NuxtLayout>
      <ThemeSwitcher />
      <NuxtPage :keepalive="{ include: ['loginSignIn', 'loginRegist'] }" />
    </NuxtLayout>
    <AppCustomerService />
  </div>
</template>

<style>
.page-enter-active,
.page-leave-active {
  transition: all 0.2s;
}

.page-enter-from,
.page-leave-to {
  opacity: 0;
}
</style>
